import { XCells, XSheet } from "@/ts/base/schema";
import { RefGraph } from "..";
import { NodeRef, ReportRangeRef } from "../../refs";
import { GraphNodeBase } from "./GraphNodeBase";
import { IFormDataHost } from "../../service";
import { getRangeCells } from "../../report";

export default class ReportRangeRefNode extends GraphNodeBase<'report-range'> {
  get name() {
    return `${this.ref.from}:${this.ref.to}`;
  }
  get label() {
    return `[单元格范围] ${this.ref.sheet} ${this.name}`;
  }

  refs: NodeRef[] = [];
  
  get value() {
    const children = this.refs.map(ref => {
      const node = this.graph.getNodeByRef(ref);
      return node?.value;
    });
    return children;
  }
  set value(_: any) {
    throw new Error('无法修改单元格范围引用');
  }

  readonly ref: ReportRangeRef;
  readonly model: IFormDataHost;
  readonly graph: RefGraph;

  readonly sheetKey: string;
  readonly cells: (XCells & { cell: string })[];
  readonly cellRange: string[]
  readonly sheet: XSheet;
  readonly formId: string;
  needCalculate = false;
  expression = '';

  constructor(ref: ReportRangeRef, graph: RefGraph, model: IFormDataHost) {
    super('report-range');
    this.ref = ref;
    this.model = model;
    this.graph = graph;

    const sheet = graph.service.formInfo[ref.sheet];
    if (!sheet || sheet.typeName !== '工作表') {
      throw new ReferenceError(`表 ${ref.sheet} 不存在！`);
    }
    this.sheetKey = sheet.form.attributeId!;
    this.sheet = sheet.form;
    this.formId = sheet.reportId!;
    this.cellRange = getRangeCells(ref.from, ref.to);
    this.cells = this.cellRange.map(c => ({
        ...sheet.form.cells[c],
        cell: c
      }));
    
    this.parseRef();
  }

  protected parseRef() {
    for (const cell of this.cellRange) {
      this.refs.push({
        type: 'report-cell',
        name: cell,
        formId: this.formId,
        sheet: this.ref.sheet,
        cell: cell,
      });
    }
  }
}